import { defineConfig } from 'yapi-to-typescript'

const generateConfig = (name) => {
  // 根据format更改返回的数据类型
  const changeType = (target, numberKeys = []) => {
    if (typeof target !== 'object') return target
    Object.keys(target).forEach((key) => {
      const { type, format } = target[key]

      target[key].type = numberKeys.includes(key)
        ? 'number'
        : format === 'int64'
        ? 'string'
        : type
    })
    return target
  }

  const treeChange = (target, required = true, numberKeys = []) => {
    if (typeof target !== 'object') return target
    if (target.type === 'object' && target.properties) {
      // 设置类型
      changeType(target.properties, numberKeys)

      // 设置必填
      const keys = Object.keys(target.properties)
      required && (target.required = keys)
      keys.forEach((key) => {
        !numberKeys.includes(key) &&
          treeChange(target.properties[key], required, numberKeys)
      })
    } else if (target.type === 'array' && target.items) {
      treeChange(target.items, required, numberKeys)
    } else if (target.format === 'int64') {
      target.type = 'string'
    }

    return target
  }

  const preproccessInterface = (interfaceInfo) => {
    const {
      req_query,
      req_body_type,
      req_body_other,
      res_body_type,
      res_body
    } = interfaceInfo

    try {
      // 处理请求的query参数
      if (req_query.length) {
        interfaceInfo.req_query = req_query.map((item) => {
          if (
            ['appId', 'baseAppId', 'appCode', 'tenantId'].includes(item.name)
          ) {
            item.required = '0'
          }

          if (['current', 'size', 'pages', 'total'].includes(item.name)) {
            item.type = 'number'
          }

          return item
        })
      }

      // 处理请求的body参数
      if (req_body_type === 'json' && req_body_other) {
        interfaceInfo.req_body_other = JSON.stringify(
          treeChange(JSON.parse(req_body_other), false, [
            'current',
            'size',
            'pages',
            'total'
          ])
        )
      }

      // 处理返回的body参数
      if (res_body_type === 'json' && res_body) {
        interfaceInfo.res_body = JSON.stringify(
          treeChange(JSON.parse(res_body), true, [
            'current',
            'size',
            'pages',
            'total'
          ])
        )
      }
    } catch (e) {}
    return interfaceInfo
  }

  return {
    serverType: 'swagger',
    serverUrl: `https://saas.police.mixwoo.com/v2_java/${name}/v2/api-docs`,
    typesOnly: true,
    target: 'typescript',
    reactHooks: {
      enabled: false
    },
    prodEnvName: 'production',
    preproccessInterface: preproccessInterface,
    outputFilePath: (interfaceInfo) =>
      `src/api/types/${name}/${interfaceInfo._category.name}/${interfaceInfo.title}Types.d.ts`,
    dataKey: 'data',
    projects: [{ token: '', categories: [{ id: 0 }] }]
  }
}

export default defineConfig([
  // paas
  generateConfig('paas')
])
